package com.china.produce.listener;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.InitializingBean;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/7/6
 */
public class ContextReadListener implements ReadListener {

    public ServletInputStream inputStream;

    public AsyncContext asyncContext;

    public ByteArrayOutputStream byteArrayOutputStream;

    public RestClient restClient;

    public ContextReadListener(ServletInputStream inputStream, AsyncContext asyncContext, ByteArrayOutputStream byteArrayOutputStream, RestClient restClient) {
        this.inputStream = inputStream;
        this.asyncContext = asyncContext;
        this.byteArrayOutputStream = byteArrayOutputStream;
        this.restClient = restClient;
    }


    @Override
    public void onDataAvailable() throws IOException {
       byte[] data = new byte[1024];
       int length;
       while (inputStream.isReady() && (length = inputStream.read(data)) != -1) {
           byteArrayOutputStream.write(data, 0, length);
       }
    }

    @Override
    public void onAllDataRead() throws IOException {
        //处理耗时任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            String res = "";
            try {
                Map<String, Object> json = JSONObject.parseObject(byteArrayOutputStream.toString(), Map.class);
                String keyWords = (String) json.getOrDefault("my_field", "");
                Request request = new Request("POST", "_msearch");
                String headString = "{\"index\":\"async_context\"}" + System.lineSeparator();
                String dslString = "{\"size\": 5,\"query\": {\"match\": {\"my_field\":\"" + keyWords + "\"}}}" +  System.lineSeparator();
                String body = new StringBuffer().append(headString).append(dslString).toString();
                StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
                request.setEntity(entity);
                Response response = (Response) restClient.performRequest(request);
                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject responses = (JSONObject) JSONObject.parseObject(responseString).getJSONArray("responses").get(0);
                JSONArray hits = responses.getJSONObject("hits").getJSONArray("hits");
                res = JSONObject.toJSONString(hits);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return res;
        }).thenApply(ret -> {
            //查询处理啊的es数据，根据字段要求反解密
            return "decry" + ret;
        });

        HttpServletResponse response = (HttpServletResponse)asyncContext.getResponse();
        response.setStatus(200);
        PrintWriter writer = response.getWriter();
        try {
            writer.append(future.get()).flush();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        byteArrayOutputStream.reset();
        asyncContext.complete();
    }

    @Override
    public void onError(Throwable throwable) {
        System.out.println(throwable.getMessage());
    }
}
